package com.daichi.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daichi.yygh.common.exception.YyghException;
import com.daichi.yygh.common.helper.HttpRequestHelper;
import com.daichi.yygh.common.result.ResultCodeEnum;
import com.daichi.yygh.enums.OrderStatusEnum;
import com.daichi.yygh.enums.PaymentStatusEnum;
import com.daichi.yygh.enums.PaymentTypeEnum;
import com.daichi.yygh.hosp.client.HospitalFeignClient;
import com.daichi.yygh.model.order.OrderInfo;
import com.daichi.yygh.model.order.PaymentInfo;
import com.daichi.yygh.order.mapper.OrderMapper;
import com.daichi.yygh.order.mapper.PaymentMapper;
import com.daichi.yygh.order.service.OrderService;
import com.daichi.yygh.order.service.PaymentService;
import com.daichi.yygh.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentInfo> implements PaymentService {

    private final OrderMapper orderMapper;

    private final HospitalFeignClient hospitalFeignClient;

    @Autowired
    public PaymentServiceImpl(OrderMapper orderMapper, HospitalFeignClient hospitalFeignClient) {
        this.orderMapper = orderMapper;
        this.hospitalFeignClient = hospitalFeignClient;
    }

    @Override
    public void savePayment(OrderInfo orderInfo, Integer paymentType) {

        int count = this.count(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderInfo.getId())
                .eq("payment_type", paymentType));
        if (count > 0) return;

        // 保存交易记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setUpdateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + "|" + orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(orderInfo.getAmount());

        this.save(paymentInfo);

    }

    @Override
    public void paySuccess(String outTradeNo, Map<String, String> paramMap) {
        //1 根据订单编号得到支付记录
        PaymentInfo paymentInfo = this.getOne(new QueryWrapper<PaymentInfo>()
                .eq("out_trade_no", outTradeNo)
                .eq("payment_type", PaymentTypeEnum.WEIXIN.getStatus()));

        //2 更新支付记录信息
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setTradeNo(paramMap.get("transaction_id"));
        paymentInfo.setCallbackContent(paramMap.toString());
        this.updateById(paymentInfo);

        //3 根据订单号得到订单信息
        OrderInfo orderInfo = orderMapper.selectById(paymentInfo.getOrderId());
        //4 更新订单信息
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderMapper.updateById(orderInfo);

        //5 调用医院接口，更新订单支付信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
        if (result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }

    }

    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        PaymentInfo paymentInfo = this.getOne(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderId)
                .eq("payment_type", paymentType));
        return paymentInfo;
    }
}
